import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode';

// create an axios instance
const service = axios.create({
  baseURL: 'http://47.113.199.96:8888/', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['satoken'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use((res) => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
    console.log(res, 'code')
    const msg = errorCode[code] || res.data.msg || errorCode.default;
    if (code === 401) {
      MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/logout').then(() => {
          location.href = '/my-wms';
        });
      }).catch(() => {});
      return Promise.reject('无效的会话，或者会话已过期，请重新登录。');
    } if (code === 500) {
      Message({
        message: msg,
        type: 'error'
      });
      return Promise.reject(new Error(msg));
    } if (code === 4011) {
      Message({
        message: res.data.message,
        type: 'error'
      })
    } if (code === 411) {
      Message({
        message: res.data.message,
        type: 'error'
      })
    } if (code !== 200) {
      Notification.error({
        title: msg
      });
      return Promise.reject('error');
    }
    return res.data;
  },
  (error) => {
    console.log(`err${error}`);
    let { message } = error;
    if (message == 'Network Error') {
      message = '后端接口连接异常';
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时';
    } else if (message.includes('Request failed with status code')) {
      message = `系统接口${message.substr(message.length - 3)}异常`;
    }
    Message({
      message,
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  });

export default service
